package com.learn.demo.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 自定义服务端消息处理handler，需要继承HandlerAdapter
 */
public class NettyServerHandlerDemo extends ChannelInboundHandlerAdapter {

    /**
     * 读取数据事件，可以接收和处理客户端发送的消息
     * @param ctx ChannelHandlerContext上下文信息包含管道(pipeline)和通道(channel)及地址信息等
     * @param msg 客户端发送的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("ChannelHandlerContext is " + ctx);
        //netty包装的消息缓冲类，效率比NIO的ByteBuffer高
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("the msg from client is " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("the address of client is " + ctx.channel().remoteAddress());
        //普通taskQueue
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(2*1000L);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello client, the msg is send by 2 seconds after,time is " + System.currentTimeMillis(), CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(2*1000L);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello client, the msg is send by 4 seconds after,time is " + System.currentTimeMillis(), CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //定时任务scheduleTaskQueue,需要等待之前的任务执行，才会执行
        ctx.channel().eventLoop().schedule(() -> {
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello client, the msg is send by 4 seconds after,time is " + System.currentTimeMillis(), CharsetUtil.UTF_8));
        }, 0, TimeUnit.SECONDS);
        System.out.println("go on .....");
    }

    /**
     * 向客户端发送数据
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Client !".getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
